package com.ljm.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.ljm.common.Pyment;
import com.ljm.common.R;
import com.ljm.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;

@RestController
@Slf4j
public class OrderNacosController {

    @Resource
    private RestTemplate restTemplate;

    @Value("${server-url.nacos-user-service}")
    private String serverURL;

    @GetMapping(value = "/payment/nacos/{id}")
    public String getPayment(@PathVariable("id") Integer id){
        return "nacos registry,serverPort:" + serverURL + "\t id" + id;
    }


    /*  使用 ribbon + sentinel 测试实现  熔断   */
    @GetMapping("/consumer/payment/{id}")
    //@SentinelResource(value = "fallback") /// 不做任何熔断 ，降级配置  给客户的就是 error页面，不友好
    // @SentinelResource(value = "fallback",fallback ="handlerFallback" ) /// 只处理业务异常
    //@SentinelResource(value = "fallback",blockHandler ="blockHandler" ) /// 只处理sentinel 配置异常
    @SentinelResource(value = "fallback",blockHandler ="blockHandler",fallback ="handlerFallback",exceptionsToIgnore={IllegalArgumentException.class}) /// 处理业务异常,处理sentinel 配置异常
    public R paymentid(@PathVariable("id")Long id){
        String forObject = restTemplate.getForObject(serverURL + "/payment/" + id, String.class);
        if(id == 4){
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
        }else if(forObject == null){
            throw new NullPointerException("NullPointerException,该ID没有对应的记录，空指针异常！");
        }
        return R.ok().message(forObject) ;
    }
    //fallback处理方法（用于处理java程序运行中出现的异常）
    public R handlerFallback(@PathVariable("id")Long id,Throwable e){
        //Payment payment = new Payment(id,"null");
       // return  new R(444,"java运行异常，handlerFallback，exception内容:"+e.getMessage(),null);
        return  R.error().message("java运行异常，handlerFallback，exception内容:"+e.getMessage());
    }
    //blockHandler处理方法（用于处理外部访问违背sentinel控制台规则的异常）
    public R blockHandler(@PathVariable("id")Long id, BlockException exception){
        return  R.error().message("sentinel控制台限流异常，blockException:"+exception.getMessage());
    }

    /*  使用 feign + sentinel 测试实现  熔断   */
    @Autowired
    PaymentService paymentService;
    @GetMapping("/opfeign/payment/{id}")
    public R opfeignpaymentid(@PathVariable("id")Long id){
        R paymentid = paymentService.paymentid(id);
        return paymentid;
    }

}
